package com.ioftv.controller;

import com.ioftv.common.Result;
import com.ioftv.entity.*;
import com.ioftv.service.*;
import com.ioftv.util.UserContextUtil;
import com.ioftv.util.RolePermissionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 大屏数据接口Controller
 */
@RestController
@RequestMapping("/bigscreen")
public class BigscreenController {

    @Autowired
    private PlatformConfigService platformConfigService;

    @Autowired
    private BusinessStatisticsService businessStatisticsService;

    @Autowired
    private ProjectPackageService projectPackageService;

    @Autowired
    private LabelerBoxRecordService labelerBoxRecordService;

    @Autowired
    private ExcellentLabelerService excellentLabelerService;

    @Autowired
    private ProjectInfoService projectInfoService;

    @Autowired
    private QcStatisticsService qcStatisticsService;

    @Autowired
    private ManagerPerformanceService managerPerformanceService;

    @Autowired
    private MapDistributionService mapDistributionService;

    /**
     * 1. 获取平台标题
     */
    @GetMapping("/platformTitle")
    public Result<Map<String, String>> getPlatformTitle(HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        
        String title = platformConfigService.getConfigValue("platform_title", "互联网可视化平台",userId);
        Map<String, String> data = new HashMap<>();
        data.put("title", title);
        return Result.success(data);
    }

    /**
     * 更新平台标题
     */
    @PostMapping("/platformTitle/update")
    public Result<Void> updatePlatformTitle(@RequestBody Map<String, String> params, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 只有管理员可以更新平台标题
        if (!RolePermissionUtil.isAdmin(role)) {
            return Result.error("无权限操作");
        }
        
        String title = params.get("title");
        platformConfigService.updateConfigValue("platform_title", title);
        return Result.success(null);
    }

    /**
     * 2. 查询业务统计数据
     */
    @GetMapping("/countDeviceNum")
    public Result<BusinessStatistics> getBusinessStatistics(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate statDate,
            HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        
        if (statDate == null) {
            statDate = LocalDate.now();
        }
        
        BusinessStatistics statistics = businessStatisticsService.getByStatDateAndUserId(statDate, userId);
        
        if (statistics == null) {
            statistics = new BusinessStatistics();
            statistics.setTotalNum(0);
            statistics.setOrderNum(0);
            statistics.setReceivableNum(0L);
            statistics.setPaymentNum(0L);
            statistics.setTestPersonNum(0);
            statistics.setQcPersonNum(0);
        }
        
        return Result.success(statistics);
    }

    /**
     * 新增业务统计数据
     */
    @PostMapping("/countDeviceNum/save")
    public Result<Void> saveBusinessStatistics(@RequestBody BusinessStatistics statistics, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 设置用户ID
        statistics.setUserId(userId);
        
        businessStatisticsService.save(statistics);
        return Result.success(null);
    }

    /**
     * 更新业务统计数据
     */
    @PostMapping("/countDeviceNum/update")
    public Result<Void> updateBusinessStatistics(@RequestBody BusinessStatistics statistics, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 检查数据是否存在且属于当前用户
        BusinessStatistics existing = businessStatisticsService.getById(statistics.getId());
        if (existing == null || !existing.getUserId().equals(userId)) {
            // 管理员可以更新所有数据
            if (!RolePermissionUtil.isAdmin(role)) {
                return Result.error("无权限操作");
            }
        }
        
        // 设置用户ID
        statistics.setUserId(existing != null ? existing.getUserId() : userId);
        
        businessStatisticsService.updateById(statistics);
        return Result.success(null);
    }

    /**
     * 删除业务统计数据
     */
    @PostMapping("/countDeviceNum/delete")
    public Result<Void> deleteBusinessStatistics(@RequestBody Map<String, Long> params, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        Long id = params.get("id");
        
        // 检查数据是否存在且属于当前用户
        BusinessStatistics existing = businessStatisticsService.getById(id);
        if (existing == null || !existing.getUserId().equals(userId)) {
            // 管理员可以删除所有数据
            if (!RolePermissionUtil.isAdmin(role)) {
                return Result.error("无权限操作");
            }
        }
        
        businessStatisticsService.removeById(id);
        return Result.success(null);
    }

    /**
     * 3. 查询项目总览数据
     */
    @GetMapping("/countUserNum")
    public Result<Map<String, Object>> getProjectPackage(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate statDate,
            HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        
        if (statDate == null) {
            statDate = LocalDate.now();
        }
        
        ProjectPackage projectPackage = projectPackageService.getByStatDateAndUserId(statDate, userId);
        
        Map<String, Object> result = new HashMap<>();
        if (projectPackage != null) {
            result.put("totalNum", projectPackage.getTotalPackageNum());
            result.put("totalPackageNum", projectPackage.getTotalPackageNum());
            result.put("completedPackageNum", projectPackage.getCompletedPackageNum());
            result.put("uncompletedPackageNum", projectPackage.getUncompletedPackageNum());
            result.put("qcPassPackageNum", projectPackage.getQcPassPackageNum());
        } else {
            result.put("totalNum", 0);
            result.put("totalPackageNum", 0);
            result.put("completedPackageNum", 0);
            result.put("uncompletedPackageNum", 0);
            result.put("qcPassPackageNum", 0);
        }
        
        return Result.success(result);
    }

    /**
     * 新增项目总览数据
     */
    @PostMapping("/countUserNum/save")
    public Result<Void> saveProjectPackage(@RequestBody ProjectPackage projectPackage, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 设置用户ID
        projectPackage.setUserId(userId);
        
        projectPackageService.save(projectPackage);
        return Result.success(null);
    }

    /**
     * 更新项目总览数据
     */
    @PostMapping("/countUserNum/update")
    public Result<Void> updateProjectPackage(@RequestBody ProjectPackage projectPackage, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 检查数据是否存在且属于当前用户
        ProjectPackage existing = projectPackageService.getById(projectPackage.getId());
        if (existing == null || !existing.getUserId().equals(userId)) {
            // 管理员可以更新所有数据
            if (!RolePermissionUtil.isAdmin(role)) {
                return Result.error("无权限操作");
            }
        }
        
        // 设置用户ID
        projectPackage.setUserId(existing != null ? existing.getUserId() : userId);
        
        projectPackageService.updateById(projectPackage);
        return Result.success(null);
    }

    /**
     * 4. 查询标注员拉框实时数据
     */
    @GetMapping("/sbtx")
    public Result<Map<String, Object>> getLabelerBoxRecords(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate recordDate,
            @RequestParam(required = false, defaultValue = "40") Integer limit,
            HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        
        if (recordDate == null) {
            recordDate = LocalDate.now();
        }
        
        // 使用服务层方法查询数据
        List<LabelerBoxRecord> records = ((com.ioftv.service.impl.LabelerBoxRecordServiceImpl) labelerBoxRecordService)
                .getByRecordDateAndUserId(recordDate, userId, limit);
        
        Map<String, Object> result = new HashMap<>();
        result.put("list", records);
        
        return Result.success(result);
    }

    /**
     * 新增标注员拉框记录
     */
    @PostMapping("/sbtx/save")
    public Result<Void> saveLabelerBoxRecord(@RequestBody LabelerBoxRecord record, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 设置用户ID
        record.setUserId(userId);
        
        labelerBoxRecordService.save(record);
        return Result.success(null);
    }

    /**
     * 批量更新达标状态
     */
    @PostMapping("/sbtx/batchUpdateStandard")
    public Result<Void> batchUpdateStandard(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        LocalDate recordDate = LocalDate.parse(params.get("recordDate").toString());
        Integer standardValue = Integer.parseInt(params.get("standardValue").toString());
        
        // 使用服务层方法更新数据
        ((com.ioftv.service.impl.LabelerBoxRecordServiceImpl) labelerBoxRecordService)
                .batchUpdateStandardAndUserId(recordDate, standardValue, userId);
        
        return Result.success(null);
    }

    /**
     * 5. 查询优秀标注员数据
     */
    @GetMapping("/alarmNum")
    public Result<Map<String, Object>> getExcellentLabelers(
            @RequestParam(required = false) Integer month,
            @RequestParam(required = false) Integer year,
            @RequestParam(required = false, defaultValue = "10") Integer limit,
            HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        
        if (year == null) {
            year = LocalDate.now().getYear();
        }
        if (month == null) {
            month = LocalDate.now().getMonthValue();
        }
        
        // 使用服务层方法查询数据
        List<ExcellentLabeler> labelers = ((com.ioftv.service.impl.ExcellentLabelerServiceImpl) excellentLabelerService)
                .getRankingByUserId(year, month, limit, userId);
        
        List<String> nameList = labelers.stream()
                .map(ExcellentLabeler::getLabelerName)
                .collect(Collectors.toList());
        
        List<Integer> countList = labelers.stream()
                .map(ExcellentLabeler::getAnnotationCount)
                .collect(Collectors.toList());
        
        Map<String, Object> result = new HashMap<>();
        result.put("month", month);
        result.put("nameList", nameList);
        result.put("countList", countList);
        
        return Result.success(result);
    }

    /**
     * 新增优秀标注员统计
     */
    @PostMapping("/alarmNum/save")
    public Result<Void> saveExcellentLabeler(@RequestBody ExcellentLabeler labeler, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 设置用户ID
        labeler.setUserId(userId);
        
        excellentLabelerService.save(labeler);
        return Result.success(null);
    }

    /**
     * 刷新排名
     */
    @PostMapping("/alarmNum/refreshRanking")
    public Result<Void> refreshLabelerRanking(@RequestBody Map<String, Integer> params, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        Integer year = params.get("statYear");
        Integer month = params.get("statMonth");
        
        // 使用服务层方法刷新排名
        ((com.ioftv.service.impl.ExcellentLabelerServiceImpl) excellentLabelerService)
                .refreshRankingByUserId(year, month, userId);
        
        return Result.success(null);
    }

    /**
     * 6. 查询数据项目列表
     */
    @GetMapping("/ssyj")
    public Result<Map<String, Object>> getProjectList(
            @RequestParam(required = false) Integer projectStatus,
            @RequestParam(required = false, defaultValue = "40") Integer limit,
            HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        
        // 使用服务层方法查询数据
        List<ProjectInfo> projects = ((com.ioftv.service.impl.ProjectInfoServiceImpl) projectInfoService)
                .getByProjectStatusAndUserId(projectStatus, limit, userId);
        
        // 转换字段名以匹配前端
        List<Map<String, Object>> projectList = projects.stream().map(project -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", project.getId());
            map.put("clientName", project.getProjectName());
            map.put("dataVolume", project.getDataVolume());
            map.put("paymentCycle", project.getPaymentCycle());
            map.put("requiredPersonnel", project.getRequiredPersonnel() + "人");
            map.put("acceptTime", project.getAcceptTime());
            map.put("deliveryTime", project.getDeliveryTime());
            return map;
        }).collect(Collectors.toList());
        
        Map<String, Object> result = new HashMap<>();
        result.put("list", projectList);
        
        return Result.success(result);
    }

    /**
     * 新增项目
     */
    @PostMapping("/ssyj/save")
    public Result<Void> saveProject(@RequestBody ProjectInfo project, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 设置用户ID
        project.setUserId(userId);
        
        projectInfoService.save(project);
        return Result.success(null);
    }

    /**
     * 更新项目
     */
    @PostMapping("/ssyj/update")
    public Result<Void> updateProject(@RequestBody ProjectInfo project, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 检查数据是否存在且属于当前用户
        ProjectInfo existing = projectInfoService.getById(project.getId());
        if (existing == null || !existing.getUserId().equals(userId)) {
            // 管理员可以更新所有数据
            if (!RolePermissionUtil.isAdmin(role)) {
                return Result.error("无权限操作");
            }
        }
        
        // 设置用户ID
        project.setUserId(existing != null ? existing.getUserId() : userId);
        
        projectInfoService.updateById(project);
        return Result.success(null);
    }

    /**
     * 删除项目
     */
    @PostMapping("/ssyj/delete")
    public Result<Void> deleteProject(@RequestBody Map<String, Long> params, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        Long id = params.get("id");
        
        // 检查数据是否存在且属于当前用户
        ProjectInfo existing = projectInfoService.getById(id);
        if (existing == null || !existing.getUserId().equals(userId)) {
            // 管理员可以删除所有数据
            if (!RolePermissionUtil.isAdmin(role)) {
                return Result.error("无权限操作");
            }
        }
        
        projectInfoService.removeById(id);
        return Result.success(null);
    }

    /**
     * 7. 查询质检统计数据
     */
    @GetMapping("/installationPlan")
    public Result<Map<String, Object>> getQcStatistics(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate statDate,
            HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        
        if (statDate == null) {
            statDate = LocalDate.now();
        }
        
        // 使用服务层方法查询数据
        List<QcStatistics> statistics = ((com.ioftv.service.impl.QcStatisticsServiceImpl) qcStatisticsService)
                .getByStatDateAndUserId(statDate, userId);
        
        List<String> category = statistics.stream()
                .map(QcStatistics::getInspectorName)
                .collect(Collectors.toList());
        
        List<Integer> barData = statistics.stream()
                .map(QcStatistics::getCheckedCount)
                .collect(Collectors.toList());
        
        List<Integer> lineData = statistics.stream()
                .map(QcStatistics::getTotalCount)
                .collect(Collectors.toList());
        
        List<Integer> rateData = statistics.stream()
                .map(stat -> stat.getPassRate().intValue())
                .collect(Collectors.toList());
        
        Map<String, Object> result = new HashMap<>();
        result.put("category", category);
        result.put("barData", barData);
        result.put("lineData", lineData);
        result.put("rateData", rateData);
        
        return Result.success(result);
    }

    /**
     * 新增质检统计
     */
    @PostMapping("/installationPlan/save")
    public Result<Void> saveQcStatistics(@RequestBody QcStatistics statistics, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 设置用户ID
        statistics.setUserId(userId);
        
        qcStatisticsService.save(statistics);
        return Result.success(null);
    }

    /**
     * 8. 查询优秀项目经理排行
     */
    @GetMapping("/ranking")
    public Result<List<Map<String, Object>>> getManagerRanking(
            @RequestParam(required = false) Integer month,
            @RequestParam(required = false) Integer year,
            @RequestParam(required = false, defaultValue = "8") Integer limit,
            HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        
        if (year == null) {
            year = LocalDate.now().getYear();
        }
        if (month == null) {
            month = LocalDate.now().getMonthValue();
        }
        
        // 使用服务层方法查询数据
        List<ManagerPerformance> performances = ((com.ioftv.service.impl.ManagerPerformanceServiceImpl) managerPerformanceService)
                .getRankingByUserId(year, month, limit, userId);
        
        List<Map<String, Object>> result = performances.stream().map(performance -> {
            Map<String, Object> map = new HashMap<>();
            map.put("name", performance.getManagerName());
            map.put("value", performance.getCompletedCount());
            return map;
        }).collect(Collectors.toList());
        
        return Result.success(result);
    }

    /**
     * 新增项目经理绩效
     */
    @PostMapping("/ranking/save")
    public Result<Void> saveManagerPerformance(@RequestBody ManagerPerformance performance, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 设置用户ID
        performance.setUserId(userId);
        
        managerPerformanceService.save(performance);
        return Result.success(null);
    }

    /**
     * 刷新项目经理排名
     */
    @PostMapping("/ranking/refreshRanking")
    public Result<Void> refreshManagerRanking(@RequestBody Map<String, Integer> params, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        Integer year = params.get("statYear");
        Integer month = params.get("statMonth");
        
        // 使用服务层方法刷新排名
        ((com.ioftv.service.impl.ManagerPerformanceServiceImpl) managerPerformanceService)
                .refreshRankingByUserId(year, month, userId);
        
        return Result.success(null);
    }

    /**
     * 9. 查询地图分布数据
     */
    @GetMapping("/centermap")
    public Result<Map<String, Object>> getMapDistribution(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate statDate,
            @RequestParam(required = false) String province,
            HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        
        if (statDate == null) {
            statDate = LocalDate.now();
        }
        
        // 使用服务层方法查询数据
        List<MapDistribution> distributions = ((com.ioftv.service.impl.MapDistributionServiceImpl) mapDistributionService)
                .getByStatDateAndUserId(statDate, province, userId);
        
        // 分组省份和城市数据
        List<Map<String, Object>> provinceData = new ArrayList<>();
        List<Map<String, Object>> cityData = new ArrayList<>();
        
        Map<String, Integer> provinceMap = new HashMap<>();
        
        for (MapDistribution dist : distributions) {
            String prov = dist.getProvince();
            provinceMap.put(prov, provinceMap.getOrDefault(prov, 0) + dist.getBusinessCount());
            
            if (dist.getCity() != null) {
                Map<String, Object> cityMap = new HashMap<>();
                cityMap.put("city", dist.getCity());
                cityMap.put("businessCount", dist.getBusinessCount());
                cityMap.put("lng", dist.getLng());
                cityMap.put("lat", dist.getLat());
                cityData.add(cityMap);
            }
        }
        
        for (Map.Entry<String, Integer> entry : provinceMap.entrySet()) {
            Map<String, Object> provMap = new HashMap<>();
            provMap.put("province", entry.getKey());
            provMap.put("businessCount", entry.getValue());
            provinceData.add(provMap);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("provinceData", provinceData);
        result.put("cityData", cityData);
        
        return Result.success(result);
    }

    /**
     * 更新地图数据
     */
    @PostMapping("/centermap/update")
    public Result<Void> updateMapDistribution(@RequestBody MapDistribution distribution, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 设置用户ID
        distribution.setUserId(userId);
        
        mapDistributionService.saveOrUpdate(distribution);
        return Result.success(null);
    }
}